<?php

namespace other;

use think\Db;
use think\db\Connection;
use think\Env;
use think\Exception;

class ShopingConn
{
    /**
     * @var Connection
     */
    private static $conn = null;


    /**
     * 数据库链接
     * @return Connection|null
     * @throws Exception
     */
    static function getConn(): ?Connection
    {
        if (self::$conn === null){
            $conn = Env::get('shoping.type', 'mysql').'://'.
                Env::get('shoping.username', 'root'). ':'.
                Env::get('shoping.password', 'abc123abc').'@'.Env::get('shoping.hostname', '127.0.0.1').':3306/'.
                Env::get('shoping.database', 'shoping') .'#utf8mb4';
            self::$conn = Db::connect($conn);
        }

        return self::$conn;
    }

    /**
     * 获得最短唯一值
     * @return string
     */
    static function getRandOnlyId(): string
    {
        $onetime=1356019200;
        $runtime=time();
        $runtime=$runtime-$onetime;
        $rand=rand(0,9).rand(0,9).rand(0,9);
        $all=$rand.$runtime;

        //把10进制转为36进制的唯一ID
        return base_convert($all,10,36);
    }

    // 获取订单信息
    static function getOrderInfo($order_id){
        // 订单信息
        $info = self::getConn()->table(Table::Table_Order)->where('id', $order_id)->find();
        if ($info){
            // A站店铺信息
            $ashop = [];
            if (isset($info['shop_id']) && $shop_id = $info['shop_id']){
                $ashop = self::getConn()->table(Table::Table_Shops)->where('id',$shop_id)->find();
            }


        }
    }

    /**
     * 群消息提醒
     * @param $msg
     * @param $key
     * @return void
     */
    static public function wechatRobot($msg,$key = '079e25fb-dee9-4f37-8f88-bc30f63b3bb5'){
        if (is_array($msg)){
            $msg = json_encode($msg);
        }

        if (!is_string($msg)){
            return;
        }

        $url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key='.$key;
        $headers = ['Content-Type: application/json'];
        $data = [
            'msgtype' => 'text',
            'text' => [
                'content' => $msg,
            ],
        ];

        $postBody = json_encode($data);

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);//设置请求头
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postBody);//设置请求体
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');//使用一个自定义的请求信息来代替"GET"或"HEAD"作为HTTP请求。(这个加不加没啥影响)
        curl_exec($curl);
        curl_close($curl);
    }
}
